
//
//  AVPlayerManager.m
//  MusicPlayer
//
//  Created by lanou3g on 16/5/11.
//  Copyright © 2016年 韩宏. All rights reserved.
//

#import "AVPlayerManager.h"

@interface AVPlayerManager ()

//播放器
@property (nonatomic, strong) AVPlayer *avPlayer;
//正在播放的url
@property (nonatomic, strong) NSString *currentUrl;
//计时器
@property (nonatomic, strong) NSTimer *myTimer;

@end

static AVPlayerManager *avPlayerManager = nil;

@implementation AVPlayerManager

+ (AVPlayerManager *)shareHandle
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (avPlayerManager == nil) {
            avPlayerManager = [[AVPlayerManager alloc] init];
        }
    });
    return avPlayerManager;
}

- (instancetype)init
{
    if (self = [super init]) {
        _status = AVPlayerPlaying;
        _myTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_myTimer forMode:NSRunLoopCommonModes];
        //暂停
        _myTimer.fireDate = [NSDate distantFuture];
        //添加歌曲播放完成通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(avPlayerDidFinishPlay:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

//接收到歌曲播放完成通知
- (void)avPlayerDidFinishPlay:(NSNotification *)notification
{
    if ([_delegate respondsToSelector:@selector(playFinished)]) {
        [_delegate playFinished];
    }
}

//定时器
- (void)timer:(NSTimer *)sender
{
    //执行代理方法
    if ([_delegate respondsToSelector:@selector(changeTime:)]) {
        [_delegate changeTime:self.currentTime];
    }
}

- (CGFloat)currentTime
{
    //计算当前的播放时间
    CGFloat time = _avPlayer.currentItem.currentTime.value / _avPlayer.currentTime.timescale;
    return time;
}

//播放url
- (void)playWithMusicUrl:(NSString *)musicUrl
{
    //AVPlayerItem封装一个item让avplayer自己播放
    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:musicUrl]];
    if (_avPlayer == nil) {
        //添加状态监控KVO
        [_avPlayer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        _avPlayer = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    } else {
        //替换现在正在播放的歌曲
        [self.avPlayer replaceCurrentItemWithPlayerItem:playerItem];
    }
    _currentUrl = musicUrl;
    
    
    //播放
    [_avPlayer play];
    //启动timer,要启动的时间已经过去了
    _myTimer.fireDate = [NSDate distantPast];
}

//观察到AVplayer status变化
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerStatus status = [change[@"new"] integerValue];
    switch (status) {
        case AVPlayerStatusReadyToPlay:
            _status = AVPlayerPlaying;
            break;
        case AVPlayerStatusFailed:
            _status = AVPlayerStop;
            //暂停定时器
            _myTimer.fireDate = [NSDate distantFuture];
            break;
        case AVPlayerStatusUnknown:
            break;
    }
}

//播放
- (void)play
{
    if (_status == AVPlayerPause) {
        [_avPlayer play];
        _status = AVPlayerPlaying;
        //启动定时器
        _myTimer.fireDate = [NSDate distantPast];
    }
}

//暂停
- (void)pause
{
    if (_status == AVPlayerPlaying) {
        [_avPlayer pause];
        _status = AVPlayerPause;
        //暂停timer
        _myTimer.fireDate = [NSDate distantFuture];
    }
}

//根据时间播放歌曲, 跳转到具体的和时间点播放
- (void)seekToTime:(CGFloat)time
{
    //参数 1.value 用second * timescale计算出    2.timescale比例
    [_avPlayer seekToTime:CMTimeMake(time * _avPlayer.currentItem.currentTime.timescale, _avPlayer.currentTime.timescale)];
    
}

- (CGFloat)volume
{
    return _avPlayer.volume;
}

- (void)setVolume:(CGFloat)volume
{
    _avPlayer.volume = volume;
}

@end
